import React, { useState, useEffect } from 'react';
import { Card } from '../../components/Card';
import { Button } from '../../components/Button';
import { Modal } from '../../components/Modal';
import './ContentSection.css';

const LONGEVITY_CONTENT = window.LONGEVITY_CONTENT || [];

export const ContentSection = () => {
  const [userContent, setUserContent] = useState([]);
  const [favorites, setFavorites] = useState([]);
  const [filter, setFilter] = useState('all');
  const [showAddModal, setShowAddModal] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    chrome.storage.local.get(['userContent', 'favorites'], (result) => {
      setUserContent(result.userContent || []);
      setFavorites(result.favorites || []);
    });
  };

  const allContent = [...LONGEVITY_CONTENT, ...userContent];
  const filteredContent = filter === 'all' 
    ? allContent 
    : allContent.filter(item => item.category === filter);

  const categories = ['all', ...new Set(allContent.map(item => item.category).filter(Boolean))];

  return (
    <section className="content-section">
      <div className="section-header">
        <h2>Longevity Information</h2>
        <Button onClick={() => setShowAddModal(true)}>+ Add</Button>
      </div>

      <div className="filter-tabs">
        {categories.map(cat => (
          <button
            key={cat}
            className={`filter-btn ${filter === cat ? 'active' : ''}`}
            onClick={() => setFilter(cat)}
          >
            {cat.charAt(0).toUpperCase() + cat.slice(1)}
          </button>
        ))}
      </div>

      <div className="content-grid">
        {filteredContent.map((item) => {
          const isFavorite = favorites.includes(item.id);
          const link = item.link || (item.references && item.references[0]?.url) || '#';
          
          return (
            <Card
              key={item.id}
              className="content-card"
              onClick={() => link !== '#' && chrome.tabs.create({ url: link })}
            >
              <h3>
                {item.title}
                <button
                  className={`favorite-btn ${isFavorite ? 'active' : ''}`}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleFavorite(item.id);
                  }}
                >
                  {isFavorite ? '⭐' : '☆'}
                </button>
              </h3>
              <span className="category">{item.category || 'General'}</span>
              <p>{item.description || ''}</p>
            </Card>
          );
        })}
      </div>

      <Modal isOpen={showAddModal} onClose={() => setShowAddModal(false)} title="Add Longevity Content">
        <form onSubmit={handleAddContent}>
          <div className="form-group">
            <input type="text" name="title" placeholder="Title" required />
          </div>
          <div className="form-group">
            <input type="url" name="link" placeholder="Link (optional)" />
          </div>
          <div className="form-group">
            <textarea name="description" placeholder="Description" rows="4"></textarea>
          </div>
          <div className="form-group">
            <input type="text" name="category" placeholder="Category" defaultValue="Custom" />
          </div>
          <Button type="submit">Add Content</Button>
        </form>
      </Modal>
    </section>
  );

  async function handleFavorite(id) {
    const newFavorites = favorites.includes(id)
      ? favorites.filter(f => f !== id)
      : [...favorites, id];
    
    await chrome.storage.local.set({ favorites: newFavorites });
    setFavorites(newFavorites);
  }

  async function handleAddContent(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const newContent = {
      id: `user-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: formData.get('title'),
      link: formData.get('link') || '',
      description: formData.get('description') || '',
      category: formData.get('category') || 'Custom',
      timestamp: Date.now()
    };

    const updatedContent = [...userContent, newContent];
    await chrome.storage.local.set({ userContent: updatedContent });
    setUserContent(updatedContent);
    setShowAddModal(false);
    e.target.reset();
  }
};

